﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Citi.SecurityHelper
{
    public class ImpersonateCitiUser
    {
        /// <summary>
        /// Log as impersonate user. Soeid must be created through Citi Encrypt Tool
        /// </summary>
        /// <param name="soeid">SoeId WITHOUT domain</param>
        /// <param name="robotUsername">User to access Encryption Folder. DOMAIN\USER</param>
        /// <param name="robotPassword">User password to access Encryption Folder</param>
        /// <returns>Impersonated user object</returns>
        public static ImpersonateUser GetImpersonateUser(string soeid, string robotUsername, string robotPassword)
        {
            var impersonate = new ImpersonateUser();

            if (!string.IsNullOrWhiteSpace(soeid))
            {
                var encryptedLines = CitiPasswordFile.GetDecryptedUserText(soeid, LoginType.ActiveDirectory, robotUsername, robotPassword);

                if (encryptedLines.Count() != 2)
                    throw new Exception(string.Format("File for user '{0}' is wrong or corrupted. Please regenerate the .pwd file in Citi Encrypt Tool", soeid));

                var splitedUser = encryptedLines.First().Split('\\');

                if (splitedUser.Count() != 2)
                    throw new Exception(string.Format(@"File for user '{0}' is wrong or corrupted. The .pwd file for Active Directory must have DOMAIN. e.g. LAC\AB12345 ", soeid));

                impersonate.Impersonate(splitedUser.First(), splitedUser.Last(), encryptedLines.Last());
            }

            return impersonate;
        }
    }
}
